<?php
namespace App\Service\Admin;

use Illuminate\Support\Facades\DB;

class UserService extends BaseService
{
    //用户

    /**
     * 用户登录
     * @param int $roleType 1用户，2代理商，3管理员
     */
    public function dologin($roleType, $uname, $upwd)
    {
        $errPas = [
            'uname' => $uname,
            'upwd' => $upwd,
        ];
        if (!$uname || !$upwd) {
            $errPas['errMsg'] = '参数错误';
            $this->loginMsg($errPas);
            return $this->toback(-2, '参数错误');
        }
        //$resOne = $this->dbQueryOne($this->dbUser, ['del' => 0, 'role_type' => $roleType, 'uname' => $uname]);
        $resOne = (array) $this->dbConn($this->dbUser)
            ->where('del', 0)
            ->where('role_type', $roleType)
            ->where('uname', $uname)
            ->first();
        if (empty($resOne)) {
            $errPas['errMsg'] = '该用户不存在';
            $this->loginMsg($errPas);
            return $this->toback(-2, '该用户不存在');
        }
        if ($resOne['passwd'] != md5($upwd)) {
            $errPas['errMsg'] = '密码错误';
            $this->loginMsg($errPas);
            return $this->toback(-2, '密码错误');
        }
        $errPas['uid'] = $resOne['id'];
        $errPas['token'] = toToken();
        $this->loginMsg($errPas);
        $resData = [
            'token' => $errPas['token'],
        ];
        return $this->toback(0, '', $resData);
    }

    /**
     * 用户信息
     */
    public function getInfo($token)
    {
        $logOne = (array) DB::table($this->dbUlog)
            ->where('token', $token)
            ->orderBy('id', 'desc')
            ->first();
        if (empty($logOne)) {
            return $this->toback(-2, '没有登录');
        }
        $res = (array) DB::table($this->dbUser)
            ->select('id', 'uname', 'realname', 'role_type', 'phone', 'email', 'balance', 'avatar', 'cid')
            ->where('id', $logOne['uid'])
            ->first();
        if (empty($res)) {
            return $this->toback(-2, '用户不存在');
        }
        $res['balance'] = $res['balance'] ? $res['balance'] / 100 : 0;
        //公司信息
        $comOne = (array) $this->dbConn($this->dbCompany)
            ->where('id', $res['cid'])
            ->first();
        $res['cname'] = empty($comOne) ? '-' : $comOne['cname'];
        return $this->toback(0, '', $res);
    }
}